package com.shanshan.crowd.mvc.config;

import com.shanshan.crowd.constant.CrowdConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description
 * @ClassName CrowdFundingSecurityConfig
 * @Author 山山大魔王
 * @Date 2022/7/26 15:26
 * @Version 1.0
 */
@Configuration
@EnableWebSecurity
// 启用web环境的权限功能
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class CrowdFundingSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {
//        super.configure(auth);
        // 基于内存,用于测试
//        builder.inMemoryAuthentication().withUser("shanshan").password("123456").roles("ADMIN");
        // 基于数据库
        builder
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);

    }

    @Override
    protected void configure(HttpSecurity security) throws Exception {
//        super.configure(http);
        security
                .authorizeRequests()                                        // 对请求授权
                .antMatchers("/static/**")                     // 针对静态资源进行设置，无条件访问
                .permitAll()
                .antMatchers("/error.html")
                .permitAll()
                .antMatchers("/admin/page.html")           // 针对分页显示Admin数据设定访问控制    这样使用不了SpringMVC的异常映射，需要配置
//                .hasRole("经理")
                .access("hasRole('经理') or hasAuthority('user:get')")
                .anyRequest()                                               // 其他任意请求
                .authenticated()                                            // 认证后访问
                .and()
                .exceptionHandling()
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
                        httpServletResponse.setCharacterEncoding("utf-8");
                        httpServletResponse.setContentType("text/html;charset=utf-8");
                        httpServletRequest.getRequestDispatcher("/WEB-INF/templates/security-error.html").forward(httpServletRequest, httpServletResponse);
                    }
                })
                .and()
                .formLogin()                                     // 开启表单登录验证的功能
                .loginPage("/admin/to/login/page.html")           // 指定登录页面
                .permitAll()
                .loginProcessingUrl("/security/do/login.html")   // 指定处理登录请求的地址
                .permitAll()
                .usernameParameter("loginAcct")                  // 账号的请求参数名称
                .passwordParameter("userPswd")                   // 密码的请求参数名称
                .defaultSuccessUrl("/admin/to/main/page.html")   // 指定登录成功后前往的地址
                .and()
                .logout()                                        // 开启退出功能
                .logoutUrl("/security/do/logout.html")                                   // 指定退出功能地址
                .logoutSuccessUrl("/admin/to/login/page.html")                            // 指定退出成功后的地址
                .and()
                .csrf()                                          // 防跨站请求伪造功能
                .disable();// 禁用
    }
}
